<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="单号" class="w-1/2"> {{ formState?.id || '-' }}</a-descriptions-item>
          <a-descriptions-item label="生效日期" class="w-1/2"> {{ dayjs(formState?.effectiveTime).format('YYYY-MM-DD') || '-' }}</a-descriptions-item>
          <a-descriptions-item label="调价根据" class="w-1/2"> {{ formState?.reason || '-' }}</a-descriptions-item>
          <a-descriptions-item label="调价人" class="w-1/2"> {{ formState?.adjustUser || '-' }}</a-descriptions-item>
          <a-descriptions-item label="调价时间" class="w-1/2"> {{ dayjs(formState?.adjustTime).format('YYYY-MM-DD') || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <BaseTable :data-source="dataSource" column-code="000163" max-fill :extra-height="64" :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')">
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>

          <template v-if="column.dataIndex === 'ypmc'">
            <EditCell title="物品名称">
              <SelectMedicine
                :value="{ mc: record.ypmc, gg: record.gg, cj: record.cj }"
                type="物资采购"
                @select="(medicine) => onSelectMedicine(record, medicine)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'beforePrice'">
            {{ record.beforePrice ? record.beforePrice.toFixed(3) : '' }}
          </template>
          <template v-if="column.dataIndex === 'currentPrice'">
            <!-- v-input:format.3 -->
            <EditCell title="调价后零售价">
              <BaseInput
                v-model:value="record.currentPrice"
                v-input-blur:float.3
                class="text-right"
                placeholder="请输入"
                :auto-focus="record.isNew && focusCell === record.key"
                @blur="onInputBlur(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'reason'">
            <EditCell title="调价根据">
              <a-input v-model:value="record.reason" placeholder="请输入" @blur="onInputBlur(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'memo'">
            <EditCell title="备注">
              <a-input v-model:value="record.memo" placeholder="请输入" @blur="onInputBlur(record)" />
            </EditCell>
          </template>

          <template v-if="column.dataIndex === 'action'">
            <ConfirmModal @confirm="onDel(record)">
              <a-button type="text" danger size="small">删除</a-button>
            </ConfirmModal>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'
import ConfirmModal from '@/components/ConfirmModal'

const route = useRoute()
const router = useRouter()
const formState = ref({})
const loading = ref(false)
const dataSource = ref([])
const focusCell = ref('')
const onInputBlur = (res) => {
  editRow(res)
}
const getMainData = async () => {
  const { data, code } = await post('materials/comprehenive/getPriceAdjustmentHeadList', {
    //总表
    zjm: route.query.id || ''
  })
  if (code === 0) {
    formState.value = data[0]
  }
}
const onDel = async (record) => {
  if (record.id) {
    const res = await post('/materials/comprehenive/doDeletePriceAdjustmentDetail', { adjustPriceId: route.query.id || '', id: record.id })
    if (res.code !== 0) {
      message.error(res.msg)
      return
    }
    message.success(res.msg)
    dataSource.value = dataSource.value.filter((item) => item.key !== record.key)
  } else {
    dataSource.value = dataSource.value.filter((item) => item.key !== record.key)
    message.success('删除成功')
  }
}

const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row) => {
  const rows = {
    adjustPriceId: route.query.id || '',
    ...row
  }
  const { code, msg } = await post('/materials/comprehenive/doSavePriceAdjustmentDetail', rows)
  if (code !== 0) return message.error(msg || '操作失败')
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
  getData()
}
const onSelectMedicine = async (row, medicine) => {
  const { code, msg } = await post('/materials/comprehenive/doCheckDrugPriceAdjutmentlnfo', { adjustPriceId: route.query.id, ypbh: medicine.bh })
  if (code !== 0) return message.error(msg)
  row.cj = medicine.cj
  row.gg = medicine.gg
  row.dw = medicine.dw
  row.ypmc = medicine.mc
  row.ypbh = medicine.bh
  row.beforePrice = medicine.dj
  row.reason = formState.value?.reason

  focusCell.value = row.key
  editRow(row)
}
//添加行
const addRow = async () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true }
  dataSource.value.push(addRow)
}

const getData = async () => {
  loading.value = true
  const { data, code } = await post('/materials/comprehenive/getPriceAdjustmentDetailList', {
    adjustPriceId: route.query.id || '',
    pageNum: 1,
    pageSize: 999
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data.map((item) => {
      return {
        ...item,
        key: item.id,
        currentPrice: item.currentPrice.toFixed(3)
      }
    })
  }
}
const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    if (item.ypbh && item.currentPrice) {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}

watch(
  () => route.query,
  () => {
    if (route.query?.id) {
      getMainData()
      getData()
      if (dataSource.value.length === 0) {
        addRow()
      }
    }
  },
  {
    immediate: true
  }
)
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
